﻿using System.Diagnostics;
using System.Linq;
using log4net;
using Reactor.Exceptions;

namespace Reactor.Hosting
{
    public abstract class ServiceHostBase
    {
        #region Fields

        protected readonly ILog Log;

        #endregion

        #region Constructors

        protected ServiceHostBase()
        {
            Log = LogManager.GetLogger(GetType());
        }

        #endregion

        #region Public Methods

        public virtual void ProcessCommandLine(string[] commandLineArguments)
        {
            if (commandLineArguments.Contains("-i"))
            {
                Log.Debug("Install switch detected.");

                Install();
            }
            else if (commandLineArguments.Contains("-u"))
            {
                Log.Debug("Uninstall switch detected.");

                Uninstall();
                return;
            }

            if (commandLineArguments.Length == 0 || commandLineArguments.Contains("-run"))
            {
                Log.Debug("Run switch detected or defaulted due to no command line switches.");

                var runAsConsole = IsConsoleMode(commandLineArguments);
                if (Log.IsDebugEnabled) Log.DebugFormat("Console mode: {0}", (runAsConsole) ? "on" : "off");

                RunManagedService(runAsConsole);
            }
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        public abstract void RunManagedService(bool runAsConsole);

        public abstract void Install();

        public abstract void Uninstall();

        #endregion

        protected void AssertThatServiceLocatorExists()
        {
            if(Environment.Context.ServiceLocator == null)
                throw new FatalException("No IServiceLocator instance found in environment context.");
        }

        protected void AssertThatServiceBusExists()
        {
            if (Environment.Context.ServiceBus == null)
                throw new FatalException("No IServiceBus instance found in environment context.");
        }

        private static bool IsConsoleMode(string[] commandLineArguments)
        {
            if (Debugger.IsAttached) return true;
            if (commandLineArguments.Contains("-console") || commandLineArguments.Contains("-c")) return true;
            if (System.Environment.UserInteractive) return true;

            return false;
        }
    }
}
